#include "VsomeipServer.h"
#include <csignal>
#include <sstream>
#include <atomic>
#include <execinfo.h>  // 用于 backtrace
#include <csignal>     // 用于信号处理
#include <cxxabi.h>    // 用于 demangle C++ 符号
#include <unistd.h>
#include <stdio.h>

using namespace std;

static int stop_flag = 0;

void print_backtrace() {
    const int max_frames = 64;
    void* buffer[max_frames];
    int num_frames = backtrace(buffer, max_frames);
    char** symbols = backtrace_symbols(buffer, num_frames);

    std::cerr << "Backtrace:\n";
    for (int i = 0; i < num_frames; ++i) {
        std::cerr << symbols[i] << '\n';
    }

    free(symbols); // 必须释放内存
}

void signal_handler(int signum) {
    std::cerr << "Signal " << signum << " received ----------- " << std::endl;
    if(signum != 2)
    {
        print_backtrace();
    }
    stop_flag = 1;
}

void setupSignalHandlers() {
    signal(SIGSEGV, signal_handler);  // 段错误
    signal(SIGINT, signal_handler);  // ctrl+c
    signal(SIGABRT, signal_handler);  // abort()
    signal(SIGILL, signal_handler);   // 非法指令
    signal(SIGFPE, signal_handler);   // 浮点异常
}

int main(int argc, char **argv) 
{
    // const char* setPath = "VSOMEIP_CONFIGURATION=udp_server.json";
    // putenv(const_cast<char*>(setPath));

    //VSOMEIP_CONFIGURATION=udp_server.json ./VsomeipServer

    setupSignalHandlers();
    VsomeipServer::instance().startup();
    while(!stop_flag)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    VsomeipServer::instance().teardown();
    std::cout << "exit" << std::endl;
    return 0;
}
